package com.lyj.service.impl;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.lyj.dao.AdminDao;
import com.lyj.dao.BaseDao;
import com.lyj.dao.MessageDao;
import com.lyj.dao.OptionDao;
import com.lyj.dao.QuestionDao;
import com.lyj.dao.QuestionnaireDao;
import com.lyj.dao.RecordDao;
import com.lyj.dao.UserDao;
import com.lyj.service.BaseService;

import jdk.nashorn.internal.ir.annotations.Reference;

/**
 * 
 * @author 李艺江
 * @version 创建时间：2019年5月6日 下午10:51:00
 */

@SuppressWarnings("rawtypes")
@Service("baseService")
@Lazy(true)
public class BaseServiceImpl<T> implements BaseService<T> {

	private Class clazz;

	protected BaseDao baseDao;
	
	@Resource
    protected UserDao userDao;
	
	@Resource
	protected AdminDao adminDao;
	
	@Resource
	protected QuestionnaireDao questionnaireDao;
	
	@Resource
	protected MessageDao messageDao;
	
	@Resource
	protected QuestionDao questionDao;
	
	@Resource
	protected OptionDao optionDao;
	
	@Resource
	protected RecordDao recordDao;
	
	public BaseServiceImpl() {
		System.out.println("this代表的是当前调用构造方法的对象" + this);
		System.out.println("获取当前this对象的父类信息" + this.getClass().getSuperclass());
		System.out.println("获取当前this对象的父类信息(包括泛型信息)" + this.getClass().getGenericSuperclass());
		ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
		clazz = (Class) type.getActualTypeArguments()[0];
	}

	@PostConstruct
	public void init() {
		// 根据clazz的类型，把不同的dao对象复制给baseDao对象
		String clazzName = clazz.getSimpleName();
		if(clazzName != "Object") {
			String clazzDao = clazzName.substring(0, 1).toLowerCase() + clazzName.substring(1) + "Dao";
			try {
				Field clazzField = this.getClass().getSuperclass().getDeclaredField(clazzDao);
				Field baseField = this.getClass().getSuperclass().getDeclaredField("baseDao");
				baseField.set(this, clazzField.get(this)); // baseDao就有值了
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void save(T t) {
		baseDao.save(t);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(T t) {
		baseDao.update(t);
	}

	@Override
	public void delete(Integer id) {
		baseDao.delete(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T get(Integer id) {
		return (T) baseDao.get(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> query() {
		return baseDao.query();
	}

}
